<?php

namespace App\Https\Controllers;

use Gregwar\Captcha\CaptchaBuilder;
use App\Utils\ImgCompress;
use App\Utils\Utils;
use App\Utils\DBUtil;
use App\Utils\ExcelUtils;
use Core\Https\Controller;

class UserController extends Controller
{
    private $upload_dir = "static/resources";
    function __construct()
    {
        parent::__construct();
        $this->initDB(array("dbname" => "blog"));
    }
    // 渲染模板
    public function index()
    {
        $this->render('app/view/login.html');
    }
    function home()
    {
        require 'app/view/index.html';
    }
    public function login($params)
    {
        $account = $params["account"];
        $password = $params["password"];
        // $code = strtolower($_POST["code"]);
        // 验证码验证
        //$verifyCode = strtolower($_SESSION["code"]);
        // if ($code != $verifyCode) {
        //     $this->outputData("", 400, '验证码错误');
        //     die();
        // }
        if ($account && $password) {
            $sql = "select * from blog_user where username='{$account}' and password='{$password}'";
            $result = mysqli_fetch_assoc($this->db->db_query($sql));
            if (empty($result)) {
                //echo "id: " . $$result["id"] . " - Name: " . $$result["username"] . " " . $$result["password"] . "<br>";
                $this->userError('用户不存在');
                die();
            }
            if ($result['password'] != $password) {
                $this->userError('密码错误');
                die();
            }

            $_SESSION["user_id"] = $result['id'];
            $_SESSION["username"] = $result['username'];
            $_SESSION["nikename"] = $result['nikename'];
            $avatar_url = $result['avatar_url'] ?? '';
            $_SESSION["avatar_url"] = $avatar_url;
            return $this->json(array($avatar_url));
        } else {
            $this->userError('用户不存在');
        }
    }
    public function verifyCode()
    {
        $builder = new CaptchaBuilder();
        $builder->build();
        $_SESSION['code'] = $builder->getPhrase();
        $code_path = "{$this->upload_dir}/images/captcha.jpg";
        $builder->save($code_path);
        $url = $_SERVER["HTTP_ORIGIN"];
        $code_url = "{$url}/{$code_path}?t=" . Utils::getTimestamp();
        return $this->json(array('code_url' => $code_url));
    }
    public function register($params)
    {
        $account = $params["account"];
        $password = $params["password"];
        $nikename = $params["nikename"];
        if ($account && $password && $nikename) {
            $sql = "insert into blog_user (username,password,nikename) values ('{$account}','{$password}','{$nikename}')";
            $res = $this->db->db_query($sql);
            return $this->json();
        } else {
            $this->userError("注册失败");
        }
    }
    // 获取用户信息
    public function getUserInfo()
    {
        $info  = array("user_id" => $_SESSION['user_id'], "account" => $_SESSION['username'], "nikename" => $_SESSION['nikename'], "avatar_url" => $_SESSION['avatar_url'] ?? '');
        return $this->json($info);
    }
    // 修改用户头像
    public function editAvatar()
    {
        $url = $this->uploadImg();
        $sql = "update blog_user set avatar_url = '{$url}' where id = {$_SESSION['user_id']}";
        $res = $this->db->db_query($sql);
        $_SESSION['avatar_url'] = $url;
        return $this->outputData(["url" => $url]);
    }
    public function queryArticle($params)
    {
        if (isset($params['id'])) {
            $id = $params['id'];
            $user_id = $_SESSION['user_id'];
            $sql = "select blog_article.*,blog_tag.name as tag_name from blog_article inner join blog_tag on blog_tag.id = blog_article.tag_id where blog_article.id = {$id}";
            $sql_tag = "select * from blog_tag where user_id = {$user_id}";
            $article = mysqli_fetch_assoc($this->db->db_query($sql));
            $tags = mysqli_fetch_all($this->db->db_query($sql_tag), MYSQLI_ASSOC);
            $articleInfo = array("article" => $article, "tags" => $tags);
            return $this->json($articleInfo);
        } else {
            //向上取整
            $pageCount = ceil($this->getArticleCount() / 10);
            $pageNum = $params['pageNum'] ?? 1;
            $user_id = $_SESSION['user_id'] ?? 1;
            $offset = ($pageNum - 1) * 10;
            $sql = "select blog_article.*,blog_tag.name as tag_name from blog_article inner join blog_tag on blog_tag.id = blog_article.tag_id where blog_article.deleted_on = 0 and blog_article.user_id = {$user_id} limit 10 offset {$offset}";
            #$sql = "select blog_article.id,blog_article.tag_id,blog_article.title,blog_article.intro,blog_article.content,blog_article.created_by,blog_tag.name as tag_name from blog_article inner join blog_tag on blog_tag.id = blog_article.tag_id where blog_article.deleted_on = 0";
            $articles =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            $articleInfo = array("pageNum" => $pageCount, "articles" => $articles);
            return $this->json($articleInfo);
        }
    }
    function searchArticle($params)
    {
        $content = $params['content'] ?? '';
        if (empty($content)) {
            $this->userError("搜索内容不能为空");
        } else {
            $user_id = $_SESSION['user_id'] ?? 1;
            $sql = "select blog_article.*,blog_tag.name as tag_name from blog_article inner join blog_tag on blog_tag.id = blog_article.tag_id where blog_article.deleted_on = 0 and blog_article.user_id = {$user_id} and blog_article.title like '%{$content}%'";
            $articles =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            $pageCount = ceil(count($articles) / 10);
            $articleInfo = array("pageNum" => $pageCount, "articles" => $articles);
            return $this->json($articleInfo);
        }
    }
    function getArticleCount()
    {
        $sql = "select Count(id) as count from blog_article where deleted_on = 0 and user_id = {$_SESSION['user_id']}";
        $res = mysqli_fetch_assoc($this->db->db_query($sql));
        $count = $res['count'];
        return (int)$count;
    }

    // 添加文章
    public function addArticle($params)
    {
        $tag_id = $params['tag_id'];
        $title = $params['title'];
        $intro = $params['intro'];
        $content = $params['content'];
        $created_by = $params['created_by'];
        $cover_image = $params['cover_image'];
        $time = Utils::getTimestamp();
        $user_id = $_SESSION['user_id'] ?? 1;
        if ($tag_id && $title && $intro && $content && $created_by) {
            $value = "{$tag_id},'{$title}','{$intro}','{$content}',{$time},'{$created_by}',{$time},'{$cover_image}','{$user_id}'";
            $sql = 'insert into blog_article (tag_id,title,intro,content,created_on,created_by,modified_on,cover_image,user_id) values (' . $value . ')';
            $res = $this->db->db_query($sql);
            $this->json("");
        } else {
            $this->userError();
        }
    }
    public function editArticle($params)
    {
        $id = $params['id'];
        $title = $params['title'];
        $intro = $params['intro'];
        $content = $params['content'];
        $created_by = $params['created_by'];
        $cover_image = $params['cover_image'];
        $tag_id = $params['tag_id'];
        if ($id && $title && $intro && $created_by && $content && $tag_id) {
            $sql = "update blog_article set title='{$title}',tag_id='$tag_id',intro='{$intro}',content='{$content}',created_by='{$created_by}',cover_image='{$cover_image}' where id = {$id}";
            $res = $this->db->db_query($sql);
            return $this->json();
        } else {
            $this->userError();
        }
    }
    // 删除文章
    public function removeArticle($params)
    {
        if (isset($params['aritileID'])) {
            $p_id = $params['aritileID'];
            $time = Utils::getTimestamp();
            $user_id = $_SESSION['user_id'] ?? 1;
            $sql = "update blog_article set deleted_on ={$time} where id = $p_id and user_id={$user_id}";
            $this->db->db_query($sql);
            $this->json();
        }
    }
    // 上传图片
    public function uploadImg()
    {
        $files = $_FILES;
        $type = array("jpg", "gif", "jpeg", "png");
        $img_name = $_FILES['file']['name'];
        // 判断上传文件类型
        $file_type = strtolower(pathinfo($img_name, PATHINFO_EXTENSION));
        if (!in_array($file_type, $type)) {
            return;
        }
        $file_path = "{$this->upload_dir}/images/{$img_name}";
        $img_url = "{$_SERVER["HTTP_ORIGIN"]}/{$file_path}?t=" . Utils::getTimestamp();
        if (move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
            $imgCompress = new ImgCompress($file_path, 0.5);
            $imgCompress->compressImg($file_path);
            return $img_url;
        } else {
            return "";
        }
    }
    // 导入数据
    public function importData($params)
    {
        $files = $_FILES;
        $type = array("xlsx", "xls");
        $file_name = $_FILES['file']['name'];
        // 判断上传文件类型
        $file_type = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        if (!in_array($file_type, $type)) {
            $this->userError();
        }
        // $file_path = "{$this->upload_dir}/export.xlsx";
        $file_path = $_FILES['file']['tmp_name'];

        $excel = new ExcelUtils();
        $data = $excel->createExcel($file_path);
        $time = Utils::getTimestamp();
        $user_id = $_SESSION["user_id"];
        foreach ($data as $articles) {
            $title = $articles[0];
            $intro = $articles[1];
            $content = $articles[2];
            $created_on = $articles[3];
            $created_by = $articles[4];
            $cover_img = $articles[5];
            $tag_name = $articles[6];
            if ($tag_name != null) {
                $sql = "insert into blog_tag (name, created_on,user_id) values ('{$tag_name}', {$time},{$user_id})";
                $res =  $this->db->db_query($sql);
                if ($res == false) {
                    $this->outputData("", 400, "导入失败");
                    break;
                    die();
                }
                $sql = "select id from blog_tag where name='{$tag_name}' and user_id={$user_id}";
                $tag_id =  mysqli_fetch_assoc($this->db->db_query($sql))["id"];
                $value = "{$tag_id},'{$title}','{$intro}','{$content}',{$created_on},'{$created_by}','{$cover_img}','{$user_id}'";
                $sql = 'insert into blog_article (tag_id,title,intro,content,created_on,created_by,cover_image,user_id) values (' . $value . ')';
                $this->db->db_query($sql);
            }
        }
        return $this->json();
    }
    // 导出数据
    public function exportData($params)
    {
        $data = $_POST;
        $file_name = "export.xlsx";
        $file_path = "{$this->upload_dir}/{$file_name}";
        $excel = new ExcelUtils();
        $excel->exportExcel($file_path, $data);
        $url = "{$_SERVER["HTTP_ORIGIN"]}/{$file_path}";
        return $this->json();
    }
    // 查询标签
    public function queryTags($params)
    {
        $user_id = $_SESSION['user_id'] ?? 1;
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            $sql = "select * from blog_tag where id = {$id} and deleted_on = 0 and user_id = {$user_id}";
            $tag = mysqli_fetch_assoc($this->db->db_query($sql));
            return $this->json($tag);
        } else {
            $sql = "select * from blog_tag where deleted_on = 0 and user_id = {$user_id}";
            $tags =  mysqli_fetch_all($this->db->db_query($sql), MYSQLI_ASSOC);
            return $this->json($tags);
        }
    }
    // 添加标签
    public function addTag($params)
    {
        if (!isset($params['name']) && !isset($_SESSION['user_id'])) {
            return $this->userError();
        }
        $time = time();
        $name = $params['name'];
        $created_by = $params['created_by'];
        $user_id = $_SESSION['user_id'];
        $sql = "insert into blog_tag (name, created_by, created_on,user_id) values ('{$name}', '{$created_by}', {$time},{$user_id})";
        $this->db->db_query($sql);
        return $this->json();
    }
    // 修改标签
    public function editTag($params)
    {
        if (!isset($params['id']) || !isset($params['name'])) {
            return $this->userError();
        }
        $time = time();
        $id = $params['id'] ?? "";
        $name = $params['name'] ?? "";
        $created_by = $params['created_by'];
        $user_id = $_SESSION['user_id'] ?? 1;
        if ($id && $name && $created_by) {
            $sql = "update blog_tag set name = '{$name}',created_by = '{$created_by}',modified_by='{$time}' where id = {$id} and user_id = {$user_id} and deleted_on = 0";
            $res = $this->db->db_query($sql);
            return $this->json();
        } else {
            $this->userError();
        }
    }
    // 删除标签
    public function removeTag($params)
    {
        $id = $params['id'];
        if (!isset($params['id'])) {
            return $this->userError();
        }
        $time = time();
        $user_id = $_SESSION['user_id'] ?? 1;
        $sql = "update blog_tag set deleted_on = {$time} where id = {$id} and user_id = {$user_id}";
        $this->db->db_query($sql);
        return $this->json();
    }
    // 恢复删除的数据
    public function recoverData()
    {
        $sql = "update blog_article set deleted_on = 0";
        $this->db->db_query($sql);
        return $this->json();
    }
    function outputData($data, $code = 200, $msg = "成功")
    {
        Utils::response($data, $code, $msg);
    }
    function userError($msg = '参数错误')
    {
        $this->code =  400;
        $this->msg = "参数错误";
        return $this->json();
    }
}
